#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基础Repository类
提供通用的数据库操作方法
"""

import logging
from typing import List, Dict, Any, Optional
from datetime import datetime, date
from database.connect_sqlserver import SQLServerConnection


class BaseRepository:
    """基础Repository类，提供通用数据库操作"""
    
    def __init__(self, connection: SQLServerConnection):
        """
        初始化Repository
        
        Args:
            connection: 数据库连接对象
        """
        self.connection = connection
        self.logger = logging.getLogger(self.__class__.__name__)
        
        if not connection or not hasattr(connection, 'connection') or not connection.connection:
            raise ValueError("无效的数据库连接")
    
    def execute_query(self, query: str, params: tuple = None) -> List[Dict[str, Any]]:
        """
        执行查询并返回结果
        
        Args:
            query: SQL查询语句
            params: 查询参数
            
        Returns:
            List[Dict]: 查询结果列表
        """
        try:
            # 参数化查询处理
            if params:
                formatted_query = self._format_query_params(query, params)
            else:
                formatted_query = query
            
            self.logger.debug(f"执行查询: {formatted_query}")
            results = self.connection.execute_query(formatted_query)
            return results if results else []
            
        except Exception as e:
            self.logger.error(f"查询执行失败: {e}, SQL: {query}")
            raise
    
    def execute_non_query(self, query: str, params: tuple = None) -> int:
        """
        执行非查询语句（INSERT, UPDATE, DELETE）
        
        Args:
            query: SQL语句
            params: 参数
            
        Returns:
            int: 影响的行数
        """
        try:
            # 参数化查询处理
            if params:
                formatted_query = self._format_query_params(query, params)
            else:
                formatted_query = query
            
            self.logger.debug(f"执行非查询: {formatted_query}")
            result = self.connection.execute_query(formatted_query)
            return 1 if result is not None else 0
            
        except Exception as e:
            param_info = ""
            if params:
                param_types = [f"{i}:{type(p).__name__}={p}" for i, p in enumerate(params)]
                param_info = f", 参数: [{', '.join(param_types)}]"
            
            self.logger.error(f"非查询语句执行失败: {e}, SQL: {query}{param_info}")
            raise
    
    def _format_query_params(self, query: str, params: tuple) -> str:
        """
        格式化查询参数
        
        Args:
            query: 原始查询语句
            params: 参数元组
            
        Returns:
            str: 格式化后的查询语句
        """
        formatted_query = query
        for param in params:
            if isinstance(param, str):
                # 字符串参数需要加引号
                formatted_query = formatted_query.replace('?', f"'{param}'", 1)
            elif isinstance(param, (date, datetime)):
                # 日期参数转换为字符串格式
                date_str = param.strftime('%Y-%m-%d') if hasattr(param, 'strftime') else str(param)
                formatted_query = formatted_query.replace('?', f"'{date_str}'", 1)
            elif param is None:
                # NULL值处理
                formatted_query = formatted_query.replace('?', 'NULL', 1)
            else:
                # 数值参数直接转换
                formatted_query = formatted_query.replace('?', str(param), 1)
        
        return formatted_query
    
    def get_table_info(self, table_name: str) -> Dict[str, Any]:
        """
        获取表的基本信息
        
        Args:
            table_name: 表名
            
        Returns:
            Dict: 表信息
        """
        query = """
        SELECT 
            COUNT(*) as total_rows,
            MAX(CAST(GETDATE() AS DATE)) as query_date
        FROM [GP].[dbo].[{}]
        """.format(table_name)
        
        try:
            result = self.execute_query(query)
            return result[0] if result else {}
        except Exception as e:
            self.logger.warning(f"获取表 {table_name} 信息失败: {e}")
            return {}
    
    def check_table_exists(self, table_name: str) -> bool:
        """
        检查表是否存在
        
        Args:
            table_name: 表名
            
        Returns:
            bool: 表是否存在
        """
        query = """
        SELECT COUNT(*) as count
        FROM INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_NAME = ? AND TABLE_SCHEMA = 'dbo'
        """
        
        try:
            result = self.execute_query(query, (table_name,))
            return result[0]['count'] > 0 if result else False
        except Exception as e:
            self.logger.error(f"检查表 {table_name} 是否存在失败: {e}")
            return False
    
    def get_column_info(self, table_name: str) -> List[Dict[str, Any]]:
        """
        获取表的列信息
        
        Args:
            table_name: 表名
            
        Returns:
            List[Dict]: 列信息列表
        """
        query = """
        SELECT 
            COLUMN_NAME,
            DATA_TYPE,
            IS_NULLABLE,
            COLUMN_DEFAULT,
            CHARACTER_MAXIMUM_LENGTH
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_NAME = ? AND TABLE_SCHEMA = 'dbo'
        ORDER BY ORDINAL_POSITION
        """
        
        try:
            return self.execute_query(query, (table_name,))
        except Exception as e:
            self.logger.error(f"获取表 {table_name} 列信息失败: {e}")
            return []
    
    def validate_connection(self) -> bool:
        """
        验证数据库连接是否有效
        
        Returns:
            bool: 连接是否有效
        """
        try:
            result = self.execute_query("SELECT 1 as test")
            return len(result) > 0
        except Exception as e:
            self.logger.error(f"数据库连接验证失败: {e}")
            return False
